from flask import Flask, render_template, request, send_from_directory
from werkzeug.utils import secure_filename
from flask import Blueprint
import os
import uuid
import config
import yolov8
import numpy as np
from PIL import Image
import io
import requests
import json

controller = Blueprint('controller', __name__, template_folder='templates')


@controller.route('/predict', methods=['GET', 'POST'])
def predict():
    # 如果是get请求响应上传视图，post请求响应上传文件

    if (request.method == 'GET'):
        return render_template('upload.html')
    else:
        data = {
            'predict': 'false',
            'url': None
        }
        if 'file' not in request.files:
            return data
        file = request.files['file']
        # # 生成一个uuid作为文件名
        fileName = str(uuid.uuid4()) + "." + "jpg"
        image = Image.open(io.BytesIO(file.stream.read()))
        result = yolov8.yolo(source=image)
        # # os.path.join拼接地址，上传地址，f.filename获取文件名

        r: bool = result[0].verbose().startswith("(no detections)")
        data = {
            'predict': "true" if r else 'false',
            'url': None
        }
        if not r:
            im = Image.fromarray(result[0].plot())
            i = io.BytesIO()
            im.save(i, format='PNG')
            i.seek(0)
            files = {'file': i.getvalue(), "filename": "test.png"}
            response = requests.post(UPLOAD_FOLDER, files=files)
            upload_res = json.loads(response.text)
            code = upload_res.get("code")
            url = upload_res.get("data")
            if code == 200:
                data[url] = url

        return data


@controller.route('/predictByStr', methods=['GET', 'POST'])
def predictByStr():

    result = yolov8.yolo(request.json.get("file")[0])

    r: bool = result[0].verbose().startswith("(no detections)")
    static_upload_path = None
    if not r:
        im = Image.fromarray(result[0].plot())
        i = io.BytesIO()
        im.save(i, format='PNG')
        i.seek(0)
        files = {'file': i.getvalue(), "filename": "test.png"}
        response = requests.post(config.UPLOAD_FOLDER, files=files)
        upload_res = json.loads(response.text)
        code = upload_res.get("code")
        url = upload_res.get("data")
        if code == 200:
            static_upload_path = url

    data = {
        'predict': "true" if r else 'false',
        'url': static_upload_path
    }
    return data
